package com.xpgk.xpsoft.code;

import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xpgk.common.controller.BaseController;
import com.xpgk.common.kit.PubKit;
import com.xpgk.xpsoft.user.UserService;

public class CodeController extends BaseController {
	public void index() {
		keepPara();
		Kv cond = Kv.by("type =", getPara("type", "").trim()).set("dmz=", getPara("dmz")).set("dmsm like ",
				isParaBlank("dmsm") ? null : getPara("dmsm", "") + "%");
		Page<Record> pages = Db.paginate(getParaToInt("pageNum", 1), 10,
				Db.getSqlPara("xpSoftCode.findCodeList", Kv.by("cond", cond)));
		List<Record> typeList = CodeTypeService.getTypeList();
		Map<Integer, String> map = PubKit.toMap(typeList, "type", "note");
		PubKit.addColumnTo(pages.getList(), "type", map, "typeName");
		setAttr("lists", pages);
		setAttr("codeTypeList", typeList);
		setAttr("bCanAdd", UserService.hasRight(getCurUserID(), "/xpCode/add_ui"));
		setAttr("bCanEdit", UserService.hasRight(getCurUserID(), "/xpCode/edit_ui"));
		render("index.html");
		// t.OutputDelta();
	}

	// 注：定义函数名时，如"void add()",页面的展示请以_ui结尾，void add_ui() 涉及到权限问题
	// add与add_ui有同样的权限
	public void add_ui() {
		setAttr("codeTypeList", CodeTypeService.getTypeList());
		render("add.html");
	}

	// 注册
	@Before(Tx.class)
	public void add() {
		keepPara();
		Record code = GetRecord("code");
		String result = CodeService.saveCode(code);
		if (!result.equals("ok"))
			renderMsg(result, "add.html");
		else
			renderMsg("添加成功.", "add.html", true);
		add_ui();
	}

	// 修改
	public void edit_ui() {
		int id = getParaToInt("id", 0);
		Record code = Db.findById("frm_code", id);
		setAttr("code", code);
		setAttr("codeTypeList", CodeTypeService.getTypeList());
		setAttr("bEdit", 1);
		render("edit.html");
	}

	// 修改
	@Before(Tx.class)
	public void edit() {
		Record code = GetRecord("code");
		keepPara();
		setAttr("bEdit", 1);
		setAttr("codeTypeList", CodeTypeService.getTypeList());
		String result = CodeService.updateCode(code);
		if (!result.equals("ok")) {
			renderMsg(result, "edit.html");
			return;
		}
		renderMsg("修改成功.", "edit.html", true);
	}
}
